import { tgxUIAlert, tgxUIController, tgxUIWaiting } from "../../core_tgx/tgx";
import { GameUILayers } from "../../scripts/GameUILayers";
import { SubGameMgr } from "../scripts/SubGameMgr";
import { UserMgr } from "../scripts/UserMgr";
import { Layout_UICreateRoom } from "./Layout_UICreateRoom";


export class UICreateRoom extends tgxUIController {
    constructor() {
        super('ui_create_room/ui_create_room', GameUILayers.POPUP, Layout_UICreateRoom);
    }

    protected onCreated(): void {
        let layout = this.layout as Layout_UICreateRoom;
        this.onButtonEvent(layout.btnClose, () => {
            this.hide();
        });

        this.onButtonEvent(layout.btnCreate, this.onBtnCreateClicked, this);

        layout.edtName.string = this.getDefaultRoomName();
    }

    private getDefaultRoomName() {
        return UserMgr.inst.name + '的好友局';
    }

    async onBtnCreateClicked() {
        let layout = this.layout as Layout_UICreateRoom;
        if (!layout.edtName.string) {
            layout.edtName.string = this.getDefaultRoomName();
            return;
        }

        if (layout.edtName.string.length > 14) {
            tgxUIAlert.show('名称最多 14 个汉字');
            return;
        }

        if (layout.edtPassword.string.length > 16) {
            tgxUIAlert.show('密码最多16个字符');
            return;
        }

        tgxUIWaiting.show();

        let ret = await UserMgr.inst.rpc_CreateSubWorld(SubGameMgr.current.id, layout.edtName.string, layout.edtPassword.string);

        tgxUIWaiting.hide();

        if (ret.isSucc) {
            let password = layout.edtPassword.string;
            tgxUIAlert.show("创建成功，立即进入").onClick(() => {
                UserMgr.inst.doEnterSubWorld(ret.res.subWorldId,password);
            });
            this.hide();
        }
        else {
            tgxUIAlert.show(ret.err.message);
        }
    }
}